package weng.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author wengjp@ffcs.cn
 * @version Revision 1.0.0
 * @版权：福富软件 版权所有 (c) 2018
 * @创建日期：2018-09-27 16:44
 * @功能说明:
 */
public class TextFile extends ArrayList<String> {
    public static String read(String filename) {
        StringBuffer stringBuffer = new StringBuffer();

        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(new File(filename).getAbsoluteFile()));
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    stringBuffer.append(s);
                    stringBuffer.append("\n");
                }
            } finally {
                in.close();
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件" + filename + "没有找到");
        } catch (IOException e) {
            System.out.println("读取文件出现异常");
        }

        return stringBuffer.toString();
    }

    public static void write(String filename, String text) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsoluteFile());
            try {
                out.print(text);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.out.println("写入文件出现异常");
        }
    }

    public TextFile(String fileName, String splitter) {
        super(Arrays.asList(read(fileName).split(splitter)));
        if ("".equals(get(0))) {
            remove(0);
        }
    }

    public TextFile(String fileName) {
        this(fileName, "\n");
    }

    public void write(String filName) {
        try {
            PrintWriter out = new PrintWriter(new File(filName).getAbsoluteFile());
            try {
                for (String item : this) {
                    out.println(item);
                }
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.out.println("写入文件出现异常");
        }

    }


}
